<script setup lang="ts">
import LoReBox from '@/components/LoReBox.vue'
import { reactive, ref, onBeforeUnmount, onMounted } from 'vue'
import { validator, emailRule, passRule, nameRule, rexfunction } from '@/utils/index'
import type { FormInstance, } from 'element-plus'
import server from '@/utils/server'
import { ElMessage } from 'element-plus'
import LinkCom from '@/components/LinkCom.vue'
import type { propsType } from '@/components/index'

import { AES_Encrypt } from '@/utils/corpto'


const linkList: propsType = [
    {
        url: '/login',
        text: '会员登录'
    },
    {
        url: '/regins',
        text: '会员注册'
    },
    {
        url: '/',
        text: '网站首页'
    }
]

const ruleFormRef = ref<FormInstance>()


// 函数校验规则
const ruleConfig: any = {
    username: emailRule,
    password: passRule,
}

const ruleForm = reactive({
    username: '',
    password: '',
    vcode: '',
    ckpassword: ''
    // username, password, password, vcode
})

const myValidate = (rule: any, value: any, callback: any) => {
    return validator(rule, value, callback)(ruleConfig[rule.field]) // 根据键名获取对应规则匹配
}

const rules = reactive({
    username: [{ validator: myValidate, trigger: 'blur', message: '用户名错误' }],
    password: [{ validator: myValidate, trigger: 'blur' }],
    ckpassword: [{ required: true, trigger: 'blur' }],
})

let timer: NodeJS.Timer
const secound = 20
let endtime = ref(secound)
onBeforeUnmount(() => {
    clearInterval(timer)
})

const sendCode = () => {
    // 验证邮箱格式
    const flag = rexfunction(emailRule, ruleForm.username)
    if (flag) {
        timer = setInterval(() => {
            if (endtime.value - 1) {
                endtime.value -= 1
                return
            }
            endtime.value = secound
            clearInterval(timer)
        }, 1000)
        server.post('/api/user/getorgetCode', {
            username: ruleForm.username
        }).then(res => {
            if (res.errno === 1) {
                ElMessage.error(res.message)
                return
            }
            ElMessage.success(res.message)
        })
        return
    }
    ElMessage.warning('请输入邮箱')
}

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            // 确认密码是否一致
            if (ruleForm.password !== ruleForm.ckpassword) {
                ElMessage.error('密码不一致')
                return
            }
            server.post('/api/user/orgetPassword', {
                ...ruleForm,
                password: AES_Encrypt(ruleForm.password)
            }).then(res => {
                if (res.errno === 1) {
                    ElMessage.error(res.message)
                    return
                }
                resetForm(ruleFormRef.value) //清空数据
                ElMessage.success(res.message)
            })
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>
      
<template>
    <LoReBox>
        <!-- 内容盒子 -->
        <div class="flex w-full bg-white rounded-lg shadow-lg overflow-hidden mx-auto max-w-sm lg:max-w-4xl">
            <div class="hidden lg:block lg:w-1/2 bg-cover">
                <img class=" h-full" src="https://www.houdunren.com/images/question.jpeg" alt="">
            </div>
            <div class="w-full p-8 lg:w-1/2">
                <h2 class="text-2xl font-semibold text-gray-700 text-center">找回密码</h2>
                <el-divider content-position="center">请妥善保存密码</el-divider>
                <!-- f -->
                <el-form ref="ruleFormRef" label-position="top" :model="ruleForm" status-icon :rules="rules"
                    label-width="120px" hideRequiredAsterisk class="demo-ruleForm">
                    <el-form-item label="账号" prop="username">
                        <el-input v-model="ruleForm.username" placeholder="请输入邮箱" />
                    </el-form-item>
                    <el-form-item>
                        <div class="flex w-full">
                            <el-input class="w-9/12" v-model="ruleForm.vcode" placeholder="请输入验证码" />
                            <el-button :disabled="endtime < secound" @click="sendCode" class="w-1/4">{{endtime < secound
                            ? `${endtime}秒后重试` :'发送验证码'}}</el-button>
                        </div>
                    </el-form-item>

                    <el-form-item label="密码" prop="password">
                        <el-input v-model="ruleForm.password" type="password" placeholder="6~18位数字字母（需包含字母）" />
                    </el-form-item>

                    <el-form-item label="确认密码" prop="ckpassword">
                        <el-input v-model="ruleForm.ckpassword" type="password" placeholder="请确认密码" />
                    </el-form-item>
                    <el-form-item>
                        <el-button class="w-full bg-blue-400" type="primary" @click="submitForm(ruleFormRef)">重置密码
                        </el-button>
                    </el-form-item>
                </el-form>
                <div class=" flex justify-center items-end mx-4 ">
                    <LinkCom :linkList="linkList"></LinkCom>
                </div>
            </div>
        </div>
    </LoReBox>
</template>
      
<style scoped>

</style>
      